package com.example.writting.ui.words

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.writting.R

class TableAdapter : RecyclerView.Adapter<TableAdapter.RowViewHolder>() {
    private var tableData: List<List<String>> = emptyList()
    private val columnWidths = mutableListOf<Int>()

    fun updateData(data: List<List<String>>, density: Float) {
        tableData = data
        calculateColumnWidths(density)
        notifyDataSetChanged()
    }

    private fun calculateColumnWidths(density: Float) {
        if (tableData.isEmpty()) return
        columnWidths.clear()

        // 计算每列的最大宽度
        val columnCount = tableData[0].size
        for (col in 0 until columnCount) {
            var maxWidth = 0
            // 遍历每一行，找出该列中最宽的单元格
            for (row in tableData) {
                val text = row[col]
                val cellWidth = calculateTextWidth(text)
                maxWidth = maxWidth.coerceAtLeast(cellWidth)
            }
            // 转换为像素并限制最大宽度为200dp
            columnWidths.add((maxWidth.coerceAtMost(200) * density).toInt())
        }
    }

    private fun calculateTextWidth(text: String): Int {
        // 简单估算：每个中文字符约占用16dp，每个英文字符约占用8dp
        val chineseCount = text.count { it.toString().toByteArray().size > 1 }
        val englishCount = text.length - chineseCount
        return (chineseCount * 16 + englishCount * 8 + 16) // 16dp的padding
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RowViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_table_row, parent, false)
        return RowViewHolder(view)
    }

    override fun onBindViewHolder(holder: RowViewHolder, position: Int) {
        val row = tableData[position]
        holder.bind(row)
    }

    override fun getItemCount(): Int = tableData.size

    inner class RowViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val container = itemView.findViewById<android.widget.LinearLayout>(R.id.rowContainer)

        fun bind(row: List<String>) {
            container.removeAllViews()
            
            // 为每一列创建单元格
            row.forEachIndexed { index, text ->
                val cell = LayoutInflater.from(itemView.context)
                    .inflate(R.layout.item_table_cell, container, false) as TextView
                
                // 设置单元格宽度和其他属性
                cell.layoutParams = android.widget.LinearLayout.LayoutParams(
                    columnWidths[index],
                    android.widget.LinearLayout.LayoutParams.WRAP_CONTENT
                )
                cell.text = text
                
                container.addView(cell)
            }
        }
    }
} 